﻿using Aspose.Cells;
using Common.EF.Controllers;
using Common.Model;
using Common.Utility;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;
using Common.Utility.AJ.MobileConfiguration;
using Common.Utility.AJ.MobileConfiguration.WeightSystem;
using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using NPOI.XSSF.UserModel;
using Stylet;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;
using AWSV2.Models;
using AWSV2.Views;
using Yitter.IdGenerator;
using static Common.AJControls.AJMultiSelect;
using AWSV2;
using AWSV2.Models.Custom;
using Common;

namespace AWSV2.ViewModels
{
    public class WeightAccountViewModel : Screen
    {

        #region 班次相关 --阿吉 2024年11月5日15点43分

        private List<AJMultiSelectOptionItem> _turnTypes;
        public List<AJMultiSelectOptionItem> TurnTypes
        {
            get => _turnTypes;
            set => SetAndNotify(ref _turnTypes, value);
        }

        private ObservableCollection<AJMultiSelectOptionItem> _turnTypeOptions;
        public ObservableCollection<AJMultiSelectOptionItem> TurnTypeOptions
        {
            get => _turnTypeOptions;
            set => SetAndNotify(ref _turnTypeOptions, value);
        }

        #endregion

        #region 日期字段类型筛选 --阿吉 2024年9月6日14点37分

        private string _selectedDateField;
        public string SelectedDateField
        {
            get => _selectedDateField;
            set => SetAndNotify(ref _selectedDateField, value);
        }

        private ObservableCollection<AJMultiSelectOptionItem> _dateFieldOptions;
        public ObservableCollection<AJMultiSelectOptionItem> DateFieldOptions
        {
            get => _dateFieldOptions;
            set => SetAndNotify(ref _dateFieldOptions, value);
        }


        #endregion

        public class GroupFieldItem
        {
            public string Name { get; set; }
            public string Column { get; set; }
            public bool Checked { get; set; }
            public Type ColumnDataType { get; set; }
            public ObservableCollection<AJMultiSelectOptionItem> DropdownSource { get; set; }
            public bool FilterChecked { get; set; }

            private IList<AJMultiSelectOptionItem> _selected;
            public IList<AJMultiSelectOptionItem> Selected
            {
                get => _selected;
                set
                {
                    _selected = value;
                    if (_selected == null || _selected.Count == 0)
                    {
                        SearchText = string.Empty;
                    }
                    else
                    {
                        SearchText = string.Join(",", value.Select(p => p.Value?.ToString())
                            .Where(p => !string.IsNullOrWhiteSpace(p)));
                    }

                }
            }
            public string SearchText { get; set; }

        }

        private bool _viewLoaded;

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }


        private IWindowManager windowManager;

        private string dateFilter; //日期筛选，0：本日 1：本月 2：自定义 ，3 近一年
        public string DateFilter
        {
            get
            {
                return dateFilter;
            }
            set
            {
                dateFilter = value;
                if (value.Equals("0"))
                {
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
                }
                else if (value.Equals("1"))
                {
                    StartDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                    EndDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
                }
                else if (value.Equals("3"))
                {
                    var now = DateTime.Now;
                    var lastYear = new DateTime(now.AddYears(-1).Year, 1, 1);

                    StartDate = lastYear;
                    var a = new DateTime(now.Year, 1, 1);
                    var b = a.AddSeconds(-1);
                    EndDate = b;
                }
            }
        }

        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set => SetAndNotify(ref _startDate, value);
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set => SetAndNotify(ref _endDate, value);
        }


        public BindableCollection<GroupFieldItem> StatisticalList { get; } //统计对象下拉列表


        public string SelectedStatisticalObj { get; set; }

        public BindableCollection<GroupFieldItem> SelectedItems { get; set; } //选择的显示字段

        public string StatusBar { get; set; }
        public Dictionary<string, string> TemplateFieldDic { get; set; } = new Dictionary<string, string>();
        private AppSettingsSection _mainSettings;
        public Worksheet Worksheet { get; }
        public string WeighingUnit { get; }
        public List<Common.Models.WeighingRecord> WList { get; private set; } //从数据库中查询出的原始称重记录列表
        public DataTable RecordDT { get; private set; } //经过转换的称重记录表格，用来显示到列表、导出到excel

        public bool EnableQueryReport { get; set; } = false;
        public bool EnablePrintReport { get; set; } = false;
        public bool EnableExportReport { get; set; } = false;

        private bool selectAll;
        public bool SelectAll
        {
            get { return selectAll; }
            set
            {
                selectAll = value;

                //SelectedItems.Clear();

                //if (value)
                //{
                //    foreach (var item in TemplateFieldDic)
                //    {
                //        SelectedItems.Add(item.Value);
                //    }
                //}
            }
        }

        /// <summary>
        /// 这个用来存放当前表格的所有列顺序，每次执行查询重新赋值，后面导出和打印需要用这个判断显示合计字符串的列
        /// --阿吉 2023年6月20日19点24分
        /// </summary>
        private List<GroupFieldItem> _checkedFieldItems;

        public void RefreshPage()
        {
            var hasStatisticList = StatisticalList?.Count > 0 && StatisticalList.Any(p => p.Checked);
            var hasSelectedItems = SelectedItems?.Count > 0 && SelectedItems.Any(p => p.Checked);
            if (hasStatisticList && hasSelectedItems)
            {
                Query();
            }


        }

        public WeightAccountViewModel(IWindowManager windowManager)
        {
            TurnTypeOptions = new ObservableCollection<AJMultiSelectOptionItem>(AJUtil.EnumToDictionary<TurnType>(null).Select(p => new AJMultiSelectOptionItem
            {
                Label = p.Key,
                Value = p.Value
            }));

            this.windowManager = windowManager;
            _mainSettings = SettingsHelper.AWSV2Settings;
            _checkedFieldItems = new List<GroupFieldItem>();
            //初始化日期筛选选择本日
            DateFilter = "0";

            //初始化条件筛选下拉框内容列表
            StatisticalList = new BindableCollection<GroupFieldItem>();
            SelectedItems = new BindableCollection<GroupFieldItem>
        {
            new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总毛重),
                Checked = true,
                Column = "mz",
                ColumnDataType = typeof(double),
            },
            new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总皮重),
                Checked = true,
                Column = "pz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总净重),
                Checked = true,
                Column = "jz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总实重),
                Checked = true,
                Column = "sz",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总金额),
                Checked = true,
                Column = "je",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总单价),
                Checked = true,
                Column = "goodsprice",
                ColumnDataType = typeof(double),
            },new GroupFieldItem
            {
                Name = I18NService.Translate(LangKeys.总车次),
                Checked = true,
                Column = "count",
                ColumnDataType = typeof(int),
            }
        };

            WeighingUnit = _mainSettings.Settings["WeighingUnit"].TryGetString("kg");

            string rolePermission = Globalspace._currentUser?.Permission ?? string.Empty;
            if (rolePermission != null)
            {
                if (rolePermission.Contains("查询报表")) EnableQueryReport = true;
                if (rolePermission.Contains("打印报表")) EnablePrintReport = true;
                if (rolePermission.Contains("导出报表")) EnableExportReport = true;
            }

            var pageSizeItems = new List<ComboItem>();
            var sizeArray = new int[] { 10, 100, 500, 1000, 2000, 5000, 10000 };
            foreach (var size in sizeArray)
            {
                pageSizeItems.Add(new ComboItem
                {
                    Name = I18NService.Translate(LangKeys._0_条每页, size),
                    Value = size
                });
            }
            PageSizeItems = new ObservableCollection<ComboItem>(pageSizeItems);

            //初始化分页控件的页行数的大小
            SelectedPageSizeItems = PageSizeItems.FirstOrDefault();
        }

        protected override async void OnViewLoaded()
        {
            if (_viewLoaded)
            {
                return;
            }
            var pound = new PoundCfg();
            var mgr = new MobileConfigurationMgr(true)
            {
                WeightFormTemplatePath = Globalspace._weightFormTemplatePath
            };

            var _fieldsSource = await pound.InitFieldsAsync(mgr, true);

            var bhField = nameof(Common.Models.WeighingRecord.Bh);

            var dateFields = Common.Models.WeighingRecord.GetWeightWeighDateFields();

            var allDynamicFieldItems = Common.Models.WeighingRecord
                .GetDyanmicPoundFieldItems(_mainSettings, true, false);

            var columns = allDynamicFieldItems
                .Where(p => p.Field != bhField && p.IsColumnDisplay).ToList();

            DateFieldOptions = new ObservableCollection<AJMultiSelectOptionItem>(dateFields
                .Select(p => new AJMultiSelectOptionItem
                {
                    Label = allDynamicFieldItems.FirstOrDefault(q => q.Field == p)?.Label ?? p,
                    Value = p
                }));

            SelectedDateField = DateFieldOptions.FirstOrDefault().Value as string;

            foreach (var item in columns)
            {
                if (dateFields.Contains(item.Field))
                {
                    continue;
                }
                var gItem = new GroupFieldItem
                {
                    Name = item.Label,
                    Column = item.Field,
                    //// 目前默认都是字符串字段 --阿吉 2023年6月19日09点30分
                    ColumnDataType = typeof(string),
                };
                var sourceFiled = _fieldsSource.FirstOrDefault(p => p.key == item.Field);
                if (sourceFiled != null && sourceFiled.children?.Count > 0)
                {
                    gItem.DropdownSource = new ObservableCollection<AJMultiSelectOptionItem>(sourceFiled.children.Select(p => new AJMultiSelectOptionItem
                    {
                        Label = p.label,
                        Value = p.value
                    }));
                }
                else
                {
                    gItem.DropdownSource = new ObservableCollection<AJMultiSelectOptionItem>();
                }

                StatisticalList.Add(gItem);
            }

            _viewLoaded = true;

        }

        public async void QueryReport()
        {
            try
            {
                if (!StatisticalList.Any(p => p.Checked))
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择统计对象));
                    return;
                }

                if (!SelectedItems.Any(p => p.Checked))
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.请至少选择显示列));
                    return;
                }

                //初始化SQL语句的参数，查询数据库得到初始数据

                var baseFilter = new Newtonsoft.Json.Linq.JObject
                {
                    {$"{SelectedDateField}Start",StartDate.GetValueOrDefault()},
                    {$"{SelectedDateField}End",  EndDate.GetValueOrDefault()},
                    {nameof(Common.Models.WeighingRecord.IsFinish),  true},
                    {nameof(Common.Models.WeighingRecord.By20),  false},
                };

                var checkedFields = StatisticalList.Where(p => p.Checked).ToList();

                foreach (var field in checkedFields)
                {
                    if (field.FilterChecked && !string.IsNullOrWhiteSpace(field.SearchText)
                        && !baseFilter.ContainsKey(field.Column))
                    {
                        baseFilter.Add(field.Column, field.SearchText);
                    }

                }

                if (TurnTypes?.Count > 0)
                {
                    baseFilter.Add(nameof(Common.Models.WeighingRecord.TurnType),
                        JArray.FromObject(TurnTypes.Select(p => p.Value)));
                }

                using var ctrl = new WeighingRecordController();
                var pages = await ctrl.Summary(new Common.Models.WeighingRecordSummaryForm
                {
                    GroupFields = checkedFields.Select(p => p.Column).ToArray(),
                    SummaryFields = Common.Models.WeighingRecord.SumFields,
                    Filter = baseFilter
                });
                WList = AJAutoMapperService.Instance().Mapper.Map<List<Common.EF.Tables.WeighingRecord>, List<Common.Models.WeighingRecord>>(pages.Data);

                //处理数据，放入DataTable中
                var dt = new DataTable("WeighingRecord");

                //修改列类型
                //var decimalColNames = new string[] { "总毛重", "总皮重", "总净重", "总实重", "总车次" };

                _checkedFieldItems = StatisticalList.Where(p => p.Checked).Union(SelectedItems
                    .Where(p => p.Checked)).ToList();
                foreach (var item in WList)
                {
                    var row = dt.NewRow();
                    var props = item.GetType().GetRuntimeProperties();
                    foreach (var col in _checkedFieldItems)
                    {
                        if (!dt.Columns.Contains(col.Name))
                        {
                            dt.Columns.Add(col.Name, col.ColumnDataType);
                        }

                        var prop = props.FirstOrDefault(p => p.Name.Equals(col.Column, StringComparison.OrdinalIgnoreCase));
                        var colVal = prop?.GetValue(item);
                        row[col.Name] = colVal == null ? DBNull.Value : colVal;
                    }

                    dt.Rows.Add(row);
                }

                DataCount = WList.Count;//数据总数
                                        //Pages = (DataCount + PageCount - 1);
                                        //把datatable set到属性RecordDT
                RecordDT = dt;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, I18NService.Translate(LangKeys.查询错误), MessageBoxButton.OK);
            }
        }

        public void PrintReport()
        {
            if (RecordDT == null || RecordDT.Rows.Count == 0)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.当前统计列表为空));
                return;
            }

            //设置列宽
            var columnWidths = new List<double>();
            var colCount = RecordDT.Columns.Count;
            var _kh = _mainSettings.Settings["_kh"].Value;
            var _ch = _mainSettings.Settings["_ch"].Value;
            var array = new string[] { _kh, _ch };
            for (int i = 0; i < colCount; i++)
            {
                columnWidths.Add(array.Contains(RecordDT.Columns[i].ColumnName)
                    ? 80 : 70);
            }
            var ht = new AccountHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);
            var companyName = _mainSettings.Settings["CompanyName"]?.Value ?? "";
            headerTemplate = headerTemplate
                .Replace("@StartDate", ((DateTime)StartDate).ToString("yyyy/MM/dd HH:mm:ss"))
                .Replace("@EndDate", ((DateTime)EndDate).ToString("yyyy/MM/dd HH:mm:ss"))
                .Replace("@WeighingUnit", WeighingUnit)
                .Replace("称重统计表", $"{companyName}-{I18NService.Translate(LangKeys.称重统计表)}");

            var tempTable = CreateTableForExportOrPrint();

            var printControl = PrintControlFactory.Create(tempTable, columnWidths, headerTemplate);
            printControl.ShowPrintPreview();
        }

        private DataTable CreateTableForExportOrPrint()
        {
            var sumColumnNames = new Dictionary<string, string>
                {
                    {I18NService.Translate(LangKeys.总毛重) ,nameof(Common.Models.WeighingRecord.Mz)},
                    {I18NService.Translate(LangKeys.总皮重),nameof(Common.Models.WeighingRecord.Pz)},
                    {I18NService.Translate(LangKeys.总净重),nameof(Common.Models.WeighingRecord.Jz) },
                    {I18NService.Translate(LangKeys.总实重),nameof(Common.Models.WeighingRecord.Sz) },
                    {I18NService.Translate(LangKeys.总金额),nameof(Common.Models.WeighingRecord.Je) },
                    {I18NService.Translate(LangKeys.总单价),nameof(Common.Models.WeighingRecord.GoodsPrice) },
                    {I18NService.Translate(LangKeys.总车次),nameof(Common.Models.WeighingRecord.Count) },
                };

            // 增加合计行 --阿吉 2023年6月20日18点21分
            var tempTable = RecordDT.DefaultView.ToTable();
            var sumRow = tempTable.NewRow();
            var paramExp = System.Linq.Expressions.Expression.Parameter(typeof(Common.Models.WeighingRecord), "p");
            IQueryable<Common.Models.WeighingRecord> source = WList.AsQueryable();
            foreach (DataColumn column in tempTable.Columns)
            {
                if (sumColumnNames.Keys.Contains(column.Caption))
                {
                    var field = sumColumnNames[column.Caption];
                    var propInfo = typeof(Common.Models.WeighingRecord)
                        .GetRuntimeProperties()
                        .FirstOrDefault(p => p.Name.Equals(field, StringComparison.OrdinalIgnoreCase));
                    var columnExpr = System.Linq.Expressions
                        .Expression.Property(paramExp, propInfo);
                    if (field.Equals(nameof(Common.Models.WeighingRecord.Count)))
                    {
                        var lambda = System.Linq.Expressions.
                        Expression.Lambda<Func<Common.Models.WeighingRecord, int>>(columnExpr, paramExp);
                        sumRow[column.Caption] = source.Sum(lambda);
                    }
                    else
                    {
                        var lambda = System.Linq.Expressions.
                        Expression.Lambda<Func<Common.Models.WeighingRecord, decimal>>(columnExpr, paramExp);
                        sumRow[column.Caption] = source.Sum(lambda);
                    }

                }
            }

            //计算需要显示合计字符串的列
            var firstSumCol = SelectedItems.Where(p => p.Checked).FirstOrDefault()?.Name;
            var firstSumColIndex = _checkedFieldItems.FindIndex(p => p.Name == firstSumCol);
            if (firstSumColIndex == -1)
            {
                firstSumColIndex = 1;
            }
            sumRow[firstSumColIndex - 1] = I18NService.Translate(LangKeys.合计_0_,string.Empty);
            tempTable.Rows.Add(sumRow);


            return tempTable;
        }

        public void ExportReport()
        {
            try
            {
                if (RecordDT == null)
                {

                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.当前统计列表为空));
                    return;
                }

                //使用DataTable数据新建excle表格

                Workbook workbook = new Workbook();
                Worksheet worksheet = workbook.Worksheets[0];

                worksheet.Name = I18NService.Translate(LangKeys.称重统计);

                ImportTableOptions importOptions = new ImportTableOptions();
                importOptions.IsFieldNameShown = true;
                importOptions.IsHtmlString = true;

                var tempTable = CreateTableForExportOrPrint();

                worksheet.Cells.ImportData(tempTable, 0, 0, importOptions);

                #region 增加表头、格式

                Aspose.Cells.Style blodStyle = workbook.CreateStyle();
                blodStyle.Font.IsBold = true;
                StyleFlag flag = new StyleFlag();
                flag.FontBold = true;

                Aspose.Cells.Style headerStyle = workbook.CreateStyle();
                headerStyle.Font.IsBold = true;
                headerStyle.Font.Size = 16;
                headerStyle.HorizontalAlignment = TextAlignmentType.Center;

                worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

                worksheet.Cells.InsertRows(0, 3);

                worksheet.Cells.Merge(0, 0, 1, 8);
                var companyName = _mainSettings.Settings["CompanyName"]?.Value ?? "";
                worksheet.Cells["A1"].PutValue($"{companyName}-{I18NService.Translate(LangKeys.称重统计表)}");
                worksheet.Cells["A1"].SetStyle(headerStyle);
                worksheet.Cells["A2"].PutValue(I18NService.Translate(LangKeys.统计日期));
                worksheet.Cells["A2"].SetStyle(blodStyle);
                worksheet.Cells.Merge(1, 1, 1, 5);
                worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd HH:mm:ss") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd HH:mm:ss"));
                worksheet.Cells["G2"].PutValue(I18NService.Translate(LangKeys.重量单位));
                worksheet.Cells["G2"].SetStyle(blodStyle);
                worksheet.Cells["H2"].PutValue(WeighingUnit);

                worksheet.AutoFitColumns();
                #endregion

                workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

                //删掉aspose的试用版信息，删掉临时文件
                XSSFWorkbook book;
                using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
                {
                    book = new XSSFWorkbook(file);
                }
                // book.RemoveSheetAt(1);
                File.Delete(Globalspace._weighingRecordTempPath);

                //打开保存文件对话框，保存称重记录
                var fileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    CreatePrompt = true,
                    OverwritePrompt = true,
                    AddExtension = true,
                    DefaultExt = ".xlsx",
                    Filter = $"{I18NService.Translate(LangKeys.excel文件)}（.xlsx）|*.xlsx",
                    FileName = $"{I18NService.Translate(LangKeys.称重记录)}_{DateTime.Now.ToString("yyyyMMdd")}",
                };

                if (fileDialog.ShowDialog().GetValueOrDefault())
                {
                    using var file = new FileStream(fileDialog.FileName, FileMode.Create);
                    book.Write(file);
                    file.Close();
                    book.Close();
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.导出成功_0_文件路径_1_, I18NService.Translate(LangKeys.称重统计表), fileDialog.FileName));
                }
            }
            catch (Exception e)
            {
                AJLog4NetLogger.Instance().Error($"ExportReport error:{e.Message}", e);
                MessageBox.Show(e.Message, I18NService.Translate(LangKeys.导出失败), MessageBoxButton.OK);
            }
        }


        #region 分页逻辑以及属性

        /// <summary>
        /// 索引信息集合
        /// </summary>
        public ObservableCollection<PagerHandle> Indexs { get; set; } = new ObservableCollection<PagerHandle>();



        public ObservableCollection<ComboItem> PageSizeItems { get; set; }

        ComboItem _SelectedPageSizeItems;
        public ComboItem SelectedPageSizeItems
        {
            get
            {
                return _SelectedPageSizeItems;
            }
            set
            {
                if (value != null)
                {
                    _SelectedPageSizeItems = value;
                    PageCount = int.Parse(_SelectedPageSizeItems.Value.ToString());
                }
            }
        }

        /// <summary>
        /// 当前选中的索引信息
        /// </summary>
        public int CurrentIndex { get; set; } = 1;
        /// <summary>
        /// 页总数
        /// </summary>
        public int Pages { get; set; }
        /// <summary>
        /// 有效的索引按钮个数，不包含（...，最有一页这2个按钮）
        /// </summary>
        public int IndexButs { get; set; } = 3;
        /// <summary>
        /// 一页显示的行数
        /// </summary>
        public int PageCount { get; set; } = 1;
        /// <summary>
        /// 数据的总数
        /// </summary>
        public int DataCount { get; set; }


        public void LeftSide(object indexStr)
        {

            var moveIndex = CurrentIndex - 1;
            if (moveIndex < 1) return;

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void RightSide(object indexStr)
        {
            var moveIndex = CurrentIndex + 1;
            if (moveIndex > Pages) return;

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void SelectedPage(object indexStr)
        {
            string str = indexStr.ToString();

            if (string.IsNullOrEmpty(str)) return;

            if (str != "...")
            {
                CurrentIndex = int.Parse(str);
            }

            if (str == "...")
            {
                var maxIndex = Indexs.Where(p => p.IndexStr != "..." && p.IndexStr != Pages.ToString()).Max(p => int.Parse(p.IndexStr));
                CurrentIndex = maxIndex;
                SetBtns();
            }
            else
            {
                var indexInfo = Indexs.FirstOrDefault(p => p.IndexStr == str);

                //Indexs.ToList().ForEach(e => { e.ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"]; });

                //indexInfo.ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];

                QueryReport();
                if (CurrentIndex == Pages)
                {
                    SetBtns();
                }
            }

        }

        private void SetBtns()
        {
            Indexs.Clear();

            if (CurrentIndex < 1 || CurrentIndex > Pages) return;

            if (Pages <= IndexButs)
            {
                for (int i = 1; i <= Pages; i++)
                {
                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                        continue;
                    }
                    Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                }

            }
            else
            {
                int i = CurrentIndex;

                for (; i <= Pages; i++)
                {
                    if (i - CurrentIndex >= IndexButs) break;

                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                        continue;
                    }
                    Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                }
                if (i < Pages)
                {
                    Indexs.Add(new PagerHandle() { IndexStr = "..." });
                    Indexs.Add(new PagerHandle() { IndexStr = Pages.ToString() });
                }
                else if (Indexs.Count < IndexButs)//如果没有预定的IndexButs个按钮，那么就要补齐少的
                {
                    int minIdex = Indexs.Min(p => int.Parse(p.IndexStr));
                    for (int j = Indexs.Count; j < IndexButs; j++)
                    {
                        minIdex--;
                        Indexs.Insert(0, new PagerHandle() { IndexStr = (minIdex).ToString() });
                    }
                }
            }
        }

        public void Query()
        {
            CurrentIndex = 1;
            QueryReport();
            SetBtns();
        }

        #endregion 


        public void TableSorted(object sender, System.Windows.Controls.DataGridColumnEventArgs e)
        {
            //if (e.Column.SortDirection ==  null)
            //{
            //    return;
            //}

            //var colName = e.Column.Header.ToString();

            //var dic = e.Column.SortDirection.GetValueOrDefault() == System.ComponentModel.ListSortDirection.Ascending ? "ASC" : "DESC";

            //RecordDT.DefaultView.Sort = $"{colName} {dic}";

            //RecordDT = RecordDT.DefaultView.ToTable();

        }
    }
}
